package sy.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sy.model.Tad;
import sy.model.Tsuggestion;
import sy.pageModel.DataGrid;
import sy.pageModel.Json;
import sy.pageModel.PageHelper;
import sy.service.AdServiceI;
import sy.service.SuggestionAdServiceI;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/adController")
public class AdController extends BaseController {
	@Autowired
	private AdServiceI adService;
	@Autowired
	private  SuggestionAdServiceI  suggestionAdService;

    //更新广告信息
    @RequestMapping("/updatecontent")
    @ResponseBody
    public Json updatecontent(HttpServletResponse response,HttpServletRequest request, HttpSession session)throws Exception {
        Json j = new Json();
        String content=request.getParameter("content");
        String imageurl=request.getParameter("imageurl");
        String id=request.getParameter("id");
        String htmlpage=getHead(content);

        try {

            Tad tad=adService.get(id);
            if(tad!=null){
                ///将字符串写入文件
                ServletContext context=request.getSession().getServletContext();
                String realpath = context.getRealPath("/ad");
                File filelocal = new File(realpath);
                if(!filelocal.exists()) filelocal.mkdirs();

                String filename=UUID.randomUUID().toString();
                FileOutputStream out = new FileOutputStream(filelocal.getAbsolutePath()+"\\"+filename+".html");
                out.write(htmlpage.getBytes());
                out.close();
                tad.setContent(content);
                tad.setImagePath(imageurl);
                tad.setLinkAddress("/ad/"+filename+".html");

                adService.update(tad);

                j.setMsg("更新成功！");
                j.setSuccess(true);
            }else{
                j.setMsg("更新失败！");
                j.setSuccess(true);
            }


        } catch (Exception e) {
            j.setMsg("更新失败！");
            j.setSuccess(false);
            e.printStackTrace();
        }

        return j;
    }


    //发布广告信息
    @RequestMapping("/uploadcontent")
    @ResponseBody
    public Json uploadcontent(HttpServletResponse response,HttpServletRequest request, HttpSession session)throws Exception {
        Json j = new Json();
        String content=request.getParameter("content");
        String imageurl=request.getParameter("imageurl");

        String htmlpage=getHead(content);
        Tad tad=new Tad();

        try {

            ///将字符串写入文件
            ServletContext context=request.getSession().getServletContext();
            String realpath = context.getRealPath("/ad");
            File filelocal = new File(realpath);
            if(!filelocal.exists()) filelocal.mkdirs();

            String filename=UUID.randomUUID().toString();
            FileOutputStream out = new FileOutputStream(filelocal.getAbsolutePath()+"\\"+filename+".html");
            out.write(htmlpage.getBytes());
            out.close();
            tad.setContent(content);
            tad.setImagePath(imageurl);
            tad.setLinkAddress("/ad/"+filename+".html");

            adService.add(tad);

            j.setMsg("提交成功！");
            j.setSuccess(true);
        } catch (Exception e) {
            j.setMsg("提交失败！");
            j.setSuccess(false);
            e.printStackTrace();
        }

        return j;
    }


	//提交建议
	@RequestMapping("/suggetion")
	@ResponseBody
	public Json suggetion(HttpServletResponse response,HttpServletRequest request, HttpSession session) {
		Json j = new Json();
		String parm=request.getParameter("parm");
		String sug=request.getParameter("sug");
		Tsuggestion tsuggestion =new Tsuggestion();
		
		try {
			
			tsuggestion.setParm(parm);
			tsuggestion.setSug(sug);
			
			suggestionAdService.add(tsuggestion);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		j.setMsg("提交成功！");
		j.setSuccess(true);
		return j;
	}
    @RequestMapping("/editgonggaoPage")
    public String editgonggaoPage(String id, HttpServletRequest request) {
        Tad tad = adService.get(id);
        request.setAttribute("tad", tad);
        return "/admanager/updateadfile";
    }
	//获取自定义广告
	@RequestMapping("/getads")
	@ResponseBody
	public String getads(HttpServletResponse response,HttpServletRequest request){
		response.setCharacterEncoding("utf-8");
		JSONObject jsobj = new JSONObject();

		try {
			List<Tad>  tads=adService.getads();

            jsobj.put("status","1");
            jsobj.put("msg",tads);

		} catch (Exception e) {

            jsobj.put("status","0");
            jsobj.put("msg","获取失败");
		}
		return jsobj.toJSONString();
	}
	
	@RequestMapping("/dataGrid")
	@ResponseBody
	public DataGrid dataGrid(Tad tad, PageHelper ph) {
		return adService.dataGrid(tad, ph);
	}
	@RequestMapping("/delete")
	@ResponseBody
	public Json delete(String id, HttpSession session) {
		Json j = new Json();
		if (id != null ) {// 不能删除自己
			adService.delete(id);
		}
		j.setMsg("删除成功！");
		j.setSuccess(true);
		return j;
	}
	
	@RequestMapping("/batchDelete")
	@ResponseBody
	public Json batchDelete(String ids, HttpSession session) {
		Json j = new Json();
		if (ids != null && ids.length() > 0) {
			for (String id : ids.split(",")) {
				if (id != null) {
					this.delete(id, session);
				}
			}
		}
		j.setMsg("批量删除成功！");
		j.setSuccess(true);
		return j;
	}

    public  String getHead(String content){
        String head="<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>" +
                "<html>" +
                "<head>" +
                "  <meta http-equiv='Content-Type' content='text/html;' charset='gbk' />" +
                "  <meta name='viewport' content='initial-scale=1.0, user-scalable=no'>" +
                "  <meta name='apple-mobile-web-app-capable' content='yes'>" +
                "  <meta name='apple-mobile-web-app-status-bar-style' content='black'>" +
                "  <title></title>" +
                " </head><body> ";

        head+=content;


        String end="</body></html>";
        return head+=end;
    }
}
